/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Frontera;

import Entidad.Muestra;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Juan
 */
public class FMuestrasCustodia extends javax.swing.JFrame {

    /**
     * Creates new form FMuestrasCustodia
     */
    public FMuestrasCustodia(FCustodia padre, int modo) {
        initComponents();
        this.setLocationRelativeTo(null);
        this.padre = padre;
        this.modo = modo;
        tca = new TableColumnAdjuster(TResultados);
        
        if(modo == ALMACENAMIENTO)
            BRegistrar.setText("Registrar Almacenamiento");
        else if(modo == DEVOLUCION_SOBRANTES)
            BRegistrar.setText("Registrar Devolución de Sobrantes");
        else if(modo == DEVOLUCION_O_DISPOSICION_MUESTRA)
            BRegistrar.setText("Registrar Devolución o Disposición de Muestra");
        else if (modo == RADIOACTIVAS)
            BRegistrar.setText("Registrar Disposición de Muestra Radioactiva");
        
        TrabajadorCargarMuestras trabajador = new TrabajadorCargarMuestras(modo){
            @Override
            protected void done(){
                try {
                    listaMuestras = get();
                    int muestrasEncontradas = listaMuestras.size();
                    if (muestrasEncontradas == 0) {
                        JOptionPane.showMessageDialog(FMuestrasCustodia.this, "No se encontraron muestras.",
                            "Información", JOptionPane.INFORMATION_MESSAGE);
                        FMuestrasCustodia.this.cerrar();
                    }
                    LMuestrasEncontradas.setText(String.valueOf(muestrasEncontradas));
                    DefaultTableModel modelo = (DefaultTableModel) TResultados.getModel();

                    for (Muestra muestra : listaMuestras) {
                        modelo.addRow(new Object[]{String.format("SA%04d", muestra.getConsecutivoSolicitud()),
                                                String.format("%s%05d", muestra.getAbreviaturaCliente(), muestra.getCodigoAlpha()),
                                                muestra.getIdentificacion(),
                                                muestra.getCantidad(),
                                                muestra.isRadioactiva(),
                                                muestra.isMagnetica()});
                    }
                    tca.adjustColumns();
                } catch (InterruptedException | ExecutionException e) {
                    JOptionPane.showMessageDialog(FMuestrasCustodia.this, e.getMessage(),
                            "Error al cargar las muestras", JOptionPane.ERROR_MESSAGE);
                    FMuestrasCustodia.this.cerrar();
                }
            }
        };
        
        ListSelectionModel selectionModel = TResultados.getSelectionModel();
        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        selectionModel.addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                seleccionCambiada();
            }
        });
        
        trabajador.execute();
    }
    
    private void seleccionCambiada(){
        if (TResultados.getSelectedRow() == -1)
            BRegistrar.setEnabled(false);
        else
            BRegistrar.setEnabled(true);
    }
    
    public void registroExitoso(Muestra muestra) {
        int posicion = listaMuestras.indexOf(muestra);
        DefaultTableModel model = (DefaultTableModel) TResultados.getModel();
        model.removeRow(posicion);
        listaMuestras.remove(posicion);
    }
    
    private void cerrar () {
        padre.setEnabled(true);
        dispose();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        LMuestrasEncontradas = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TResultados = new javax.swing.JTable();
        BRegistrar = new javax.swing.JButton();
        BRegresar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Muestras en Custodia");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Muestras en Custodia"));

        jLabel1.setText("Muestras encontradas:");

        LMuestrasEncontradas.setText("Buscando...");

        TResultados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Solicitud", "Codigo Alpha", "Identificación", "Cantidad", "Radioactiva", "Magnética"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Boolean.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        TResultados.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(TResultados);

        BRegistrar.setText("Registrar -----");
        BRegistrar.setEnabled(false);
        BRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRegistrarActionPerformed(evt);
            }
        });

        BRegresar.setText("Regresar");
        BRegresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRegresarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 695, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(LMuestrasEncontradas))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(BRegistrar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(BRegresar)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(LMuestrasEncontradas))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BRegistrar)
                    .addComponent(BRegresar))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRegistrarActionPerformed
        if(modo == ALMACENAMIENTO)
            java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FMuestrasCustodia.this.setEnabled(false);
                new FRegistroAlmacenamiento(FMuestrasCustodia.this, listaMuestras.get(TResultados.getSelectedRow())).setVisible(true);
            }
            });
        else if (modo == DEVOLUCION_SOBRANTES)
            java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FMuestrasCustodia.this.setEnabled(false);
                new FRegistroDevolucionSobrantes(FMuestrasCustodia.this, listaMuestras.get(TResultados.getSelectedRow())).setVisible(true);
            }
            });
        else if (modo == DEVOLUCION_O_DISPOSICION_MUESTRA)
            java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FMuestrasCustodia.this.setEnabled(false);
                new FRegistroDisposicion(FMuestrasCustodia.this, listaMuestras.get(TResultados.getSelectedRow())).setVisible(true);
            }
            });
        else
            java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                FMuestrasCustodia.this.setEnabled(false);
                new FRegistroDisposicionRadioactiva(FMuestrasCustodia.this, listaMuestras.get(TResultados.getSelectedRow())).setVisible(true);
            }
            });
    }//GEN-LAST:event_BRegistrarActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        cerrar();
    }//GEN-LAST:event_formWindowClosing

    private void BRegresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRegresarActionPerformed
        cerrar();
    }//GEN-LAST:event_BRegresarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FMuestrasCustodia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FMuestrasCustodia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FMuestrasCustodia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FMuestrasCustodia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FMuestrasCustodia(null, 0).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BRegistrar;
    private javax.swing.JButton BRegresar;
    private javax.swing.JLabel LMuestrasEncontradas;
    private javax.swing.JTable TResultados;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    private ArrayList<Muestra> listaMuestras;
    public static final int ALMACENAMIENTO = 0;
    public static final int DEVOLUCION_SOBRANTES = 1;
    public static final int DEVOLUCION_O_DISPOSICION_MUESTRA = 2;
    public static final int RADIOACTIVAS = 3;
    private int modo;
    private FCustodia padre;
    private TableColumnAdjuster tca;

}
